package test.controller;

import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping(value = "/zookeeper",method = RequestMethod.POST)
public class ZookeeperController {

	@Resource(name = "curatorClient")
	private CuratorFramework client;
	@Value("${zookeeper.curator.namespace}")
	String namespace;

	@RequestMapping("/createZnode")
	public String createZnode(String path,@RequestParam(defaultValue = "")String data){
		path = "/"+path;
		List<ACL> aclList = new ArrayList<>();
		Id id = new Id("world", "anyone");
		aclList.add(new ACL(ZooDefs.Perms.ALL, id));
		try {
			client.create()
			.creatingParentsIfNeeded()  //没有父节点时 创建父节点
			.withMode(CreateMode.PERSISTENT)  //节点类型
			.withACL(aclList)   //配置权限
			.forPath(path, data.getBytes());
		} catch (Exception e) {
			e.printStackTrace();
			return "节点创建失败"+e.getMessage();
		}
		return "节点创建成功";
	}

}
